package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 负载均衡算法 --- 带有权重随机
 * @author shenguangyang
 */
public class LbRandomWeight extends LoadBalance {
    static Random random = new Random();
    public static void main(String[] args) {
        LoadBalance loadBalance = new LbRandomWeight();
        loadBalance.printf();
    }
    @Override
    public String getServer() {
        // =========================> 如果权重比较大会占用比较大内存, 同时性能低
        List<String> ips = new ArrayList<>();
        for (String ip : ServerIps.WEIGHT_LIST.keySet()) {
            Integer weight = ServerIps.WEIGHT_LIST.get(ip);
            for (int i = 0; i < weight; i++) {
                ips.add(ip);
            }
        }
        return ips.get(random.nextInt(ips.size()));
    }
}
